package com.cqhz.quwan.ui.base

import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Canvas
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.util.Log
import android.view.View
import com.blankj.utilcode.util.StringUtils
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.LoginBean
import com.cqhz.quwan.model.OrderResp
import com.cqhz.quwan.model.UserInfoBean
import com.cqhz.quwan.mvp.mall.WebViewContract
import com.cqhz.quwan.mvp.mall.WebViewPresenter
import com.cqhz.quwan.service.API
import com.cqhz.quwan.ui.activity.FootballLotteryActivity
import com.cqhz.quwan.ui.activity.GoPaymentActivity
import com.cqhz.quwan.ui.activity.RechargeActivity
import com.cqhz.quwan.ui.buy.BettingMachineActivity
import com.cqhz.quwan.ui.activity.ESportActivity
import com.cqhz.quwan.ui.login.LoginActivity
import com.cqhz.quwan.ui.main.MainActivity
import com.cqhz.quwan.ui.mine.DiamondRecordActivity
import com.cqhz.quwan.util.*
import com.google.gson.GsonBuilder
import com.tencent.smtt.sdk.ValueCallback
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebView
import com.yalantis.ucrop.util.FileUtils
import kotlinx.android.synthetic.main.activity_webview.*
import me.militch.quickcore.core.HasDaggerInject
import quickcore.webview.WebViewListener
import quickcore.webview.WebViewSetup
import java.io.File
import java.util.*
import javax.inject.Inject


class WebViewActivity : GoBackActivity(), WebViewListener, WebViewContract.View, PayEventSubscribe, LoginSubscribe, HasDaggerInject<ActivityInject> {

    @Inject
    lateinit var webViewPresenter: WebViewPresenter
    private val requestChooseFile = 0x1001
    private var valueCallbacks: ValueCallback<Array<Uri>>? = null
    private var valueCallback: ValueCallback<Uri>? = null
    private var mHandler = Handler(Looper.getMainLooper())
    private var startUrl: String? = null
    private var url: String? = null
    private var bannerId: String? = null
    private var canGoBack: Boolean = false
    private var loginBean: LoginBean? = null
    private var userInfoBean: UserInfoBean? = null

    override fun inject(t: ActivityInject?) {
        t?.inject(this)
    }

    override fun layout(): Int {
        return R.layout.activity_webview
    }

    override fun setTitleView(title: String?) {
        setTitleBarText(title ?: "")
    }

    override fun login(loginBean: LoginBean?) {
        this.loginBean = loginBean
        if (loginBean != null) {
            finish()
        }
    }

    override fun showUserInfo(userInfoBean: UserInfoBean) {
        this.userInfoBean = userInfoBean

        if (url!!.contains(API.LunTan)) {
            val nickName = userInfoBean!!.nickName// 用户的nickname
            val headAddress = if (userInfoBean!!.headAddress == null) "https://s1.ax1x.com/2018/10/12/iNkIw6.jpg" else userInfoBean!!.headAddress.getImageUrl()// 用户的头像url
            val openId = userInfoBean!!.mobile// 用户的openid
            val postData = "nickname=$nickName&avatar=$headAddress&openid=$openId"
            webView.postUrl(url, postData.toByteArray())
        }
    }

    override fun pageEnd(view: WebView?, url: String?) {
        if (url?.startsWith("${API.share}?user_id=") == true) {
            actionShare.visibility = View.VISIBLE
        } else if (url!!.startsWith(API.DDXQ) || url!!.startsWith(API.eSportOrderDetail)) {
            setTitleBarRightText("截图") {
                canGoBack = false
                checkPermissions()
            }
        } else {
            actionShare.visibility = View.GONE
        }
    }

    override fun pageStart(view: WebView?, url: String?, favicon: Bitmap?) {
        startUrl = url
    }

    override fun doPayFinish() {
        finish()
    }

    override fun showOrderInfo(orderInfo: OrderResp, periodId: String, typeId: String) {
        if (orderInfo.status == 0) {
            val intent = Intent(this, GoPaymentActivity::class.java)
            intent.putExtra(KeyContract.Amount, orderInfo.payAmount?.toDouble())
            intent.putExtra(KeyContract.ActualAmount, orderInfo.payAmount?.toDouble())
            intent.putExtra(KeyContract.PeriodNum, periodId)
            intent.putExtra(KeyContract.OrderId, orderInfo.id)
            intent.putExtra(KeyContract.LotteryName, when (orderInfo.lotteryId) {
                "11" -> "双色球"
                "14" -> "大乐透"
                "12" -> "福彩3D"
                "16" -> "排列3"
                "15" -> "七星彩"
                "21" -> "竞猜足球"
                else -> "未知"
            })
            startActivity(intent)
        }
    }

    override fun loadUrl(webView: WebView?, isWebScheme: Boolean, scheme: String?, url: String?): Boolean {
        val log = CLogger(this::class.java)
        log.e("url", url ?: "")
        if (!isWebScheme) {

        } else {
            this.webView.loadUrl(url)

        }
        return true
    }

    override fun onDownload(url: String?) {
    }

    override fun onOpenFile(`is`: Boolean, callback: ValueCallback<Array<Uri>>?, callback2: ValueCallback<Uri>?) {
    }

    override fun titleBarText(): String? {
        return intent.getStringExtra(KeyContract.Title)
    }


    @SuppressLint("JavascriptInterface")
    override fun initView() {
        LoginObserver.register(this)
        webViewPresenter.attachView(this)
        PayEventObserver.register(this)

        loginBean = APP.get()!!.loginInfo
        url = intent.getStringExtra(KeyContract.Url)

        // 所有的页面默认传入userId
        when {
            url!!.endsWith(".html") -> {
                url += "?userId=${loginBean?.userId}"
            }
            !url!!.contains(API.LunTan) && !url!!.contains("userId=") && !url!!.endsWith(".html") -> {
                url += "&userId=${loginBean?.userId}"
            }
            else -> {
            }
        }

        // 添加BannerId
        if (!StringUtils.isEmpty(intent.getStringExtra(KeyContract.BannerId))) {
            bannerId = intent.getStringExtra(KeyContract.BannerId)
        }
        when {
            bannerId != null && url!!.endsWith(".html") -> {
                url += "?bannerId=$bannerId"
            }
            bannerId != null && (url!!.contains("&userId=") || !url!!.endsWith(".html")) -> {
                url += "&bannerId=$bannerId"
            }
            else -> {
            }
        }

        val log = CLogger(this::class.java)
        log.e("url", url ?: "")

        val enableRefresh = intent.getBooleanExtra(KeyContract.EnableRefresh, true)
        refreshLayout.isEnableRefresh = enableRefresh
        val title: String? = intent.getStringExtra(KeyContract.Title)
        if (title?.isEmpty() == true) {
            titleBar.visibility = View.GONE
        }

        val dir = getDir("database", Context.MODE_PRIVATE).path
        val jsBridge = JSBridgeInterface()
        jsBridge.toPayCallBack = { orderId, periodId, typeId ->
            webViewPresenter.getOrderInfo(orderId, periodId, typeId)
        }

        // 页面跳转回调
        jsBridge.gotoPageCallBack = { pageId, param ->
            val loginInfo = APP.get()!!.loginInfo
            if (loginInfo?.userId == null) {
                val intent = Intent(this, LoginActivity::class.java)
                startActivity(intent)
            } else {// 1充值 2钻石
                when (pageId) {
                    "0" -> {//主页
                        finish()
                        MainEventObserver.pushDoCheck(param.toInt())
                    }
                    "1" -> startActivity(Intent(this, RechargeActivity::class.java))
                    "2" -> startActivity(Intent(this, DiamondRecordActivity::class.java))
                    "10" -> {// 游戏电竞
                        var intent = Intent(this, ESportActivity::class.java)
                        intent.putExtra(KeyContract.Title, "电竞")
                        intent.putExtra(KeyContract.LotteryId, pageId)// Type
                        intent.putExtra(KeyContract.Position, param)// Position 跳转的位置
                        startActivity(intent)
                    }
                    "21" -> {// 过关足球（混合投注）
                        val intent = Intent(this, FootballLotteryActivity::class.java)
                        intent.putExtra(KeyContract.LotteryId, pageId)
                        intent.putExtra(KeyContract.Position, 0)
                        startActivity(intent)
                    }
                    "22" -> {// 单关足球（单关固定）
                        val intent = Intent(this, FootballLotteryActivity::class.java)
                        intent.putExtra(KeyContract.LotteryId, pageId)
                        intent.putExtra(KeyContract.Position, 1)
                        startActivity(intent)
                    }
                    "23" -> {// 欢乐猜球
                        var intent = Intent(this, ESportActivity::class.java)
                        intent.putExtra(KeyContract.Title, "猜球")
                        intent.putExtra(KeyContract.LotteryId, pageId)// Type
                        intent.putExtra(KeyContract.Position, param)// Position 跳转的位置
                        startActivity(intent)
                    }
                }
            }
        }

        jsBridge.postOrderCallBack = {
            val gson = GsonBuilder().create()
            if (!TextUtils.isEmpty(it)) {
                val (id, payAmount) = gson.fromJson(it, OrderResp::class.java)
                val intent = Intent(this, GoPaymentActivity::class.java)
                intent.putExtra(KeyContract.Amount, java.lang.Double.valueOf(payAmount))
                intent.putExtra(KeyContract.ActualAmount, java.lang.Double.valueOf(payAmount))
                intent.putExtra(KeyContract.LotteryName, "竞猜足球-跟单")
                intent.putExtra(KeyContract.OrderId, id)
                startActivity(intent)
            }
        }
        jsBridge.toLoginCallBack = {
            if (loginBean?.userId == null) {
                val intent = Intent(this, LoginActivity::class.java)
                startActivity(intent)
            }
        }
        jsBridge.toBettingCallBack = { _, typeId ->
            val cl = APP.get()!!.currentLottery.find {
                it.id == typeId
            }
            if (cl != null) {
                val intent = Intent(this, BettingMachineActivity::class.java)
                intent.putExtra(KeyContract.PeriodNum, cl.period)
                intent.putExtra(KeyContract.LotteryId, cl.id)
                startActivity(intent)
            } else {
                showToast("网络加载失败，请重试")
            }
        }
        jsBridge.finishCallBack = {
            mHandler.post {
                if (webView.canGoBack()) {
                    webView.goBack()
                } else {
                    finish()
                }
            }
        }
        jsBridge.goHomeCallBack = {
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
        }
        jsBridge.goToTarget = {
            val clog = CLogger(this::class.java)
            clog.d("flag", it)
            if (it == "hhtz") {
                val intent = Intent(this, FootballLotteryActivity::class.java)
                intent.putExtra(KeyContract.LotteryId, "21")
                intent.putExtra(KeyContract.Position, 0)
                startActivity(intent)
            }
        }
        WebViewSetup.builder()
                .setWebViewClient(this)
                .setLocationDbPath(dir)
                .setCacheMode(WebSettings.LOAD_NO_CACHE)
                .build().setupWebView(webView)
        webView.addJavascriptInterface(jsBridge, "Android")

        initWebChromeClient()
        refreshLayout.setOnRefreshListener { rl ->
            if (url != null) {
                webView.reload()
            }
            if (rl.state.isOpening) {
                rl.finishRefresh()
            }
        }
        actionShare.setOnClickListener {
            canGoBack = true
            checkPermissions()
        }
        if (url != null) {
            if (loginBean != null && loginBean!!.userId != null && url!!.contains(API.LunTan)) {
                webViewPresenter.getUserInfo(loginBean!!.userId!!)
                return
            }
            webView.loadUrl(url)
            Log.e("h5页面", url)
        }
    }

    /**
     * 初始化WebChromeClient
     */
    private fun initWebChromeClient() {
        webView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                if (newProgress == 100) {
                    progress_bar.visibility = View.GONE// 加载完网页进度条消失
                    refreshLayout.finishRefresh()
                } else {
                    progress_bar.visibility = View.VISIBLE// 开始加载网页时显示进度条
                    progress_bar.progress = newProgress// 设置进度值
                }
            }

            // For Android 4.1
            override fun openFileChooser(uploadMsg: ValueCallback<Uri>, acceptType: String?, capture: String?) {
                if (valueCallback != null) {
                    valueCallback!!.onReceiveValue(null)
                }
                valueCallback = uploadMsg
                val i = Intent(Intent.ACTION_GET_CONTENT)
                i.addCategory(Intent.CATEGORY_OPENABLE)
                val type = if (TextUtils.isEmpty(acceptType)) "*/*" else acceptType
                i.type = type
                startActivityForResult(Intent.createChooser(i, "选择图片"), requestChooseFile)
            }

            //Android 5.0+
            @SuppressLint("NewApi")
            override fun onShowFileChooser(webView: WebView?, filePathCallback: ValueCallback<Array<Uri>>?, fileChooserParams: WebChromeClient.FileChooserParams?): Boolean {
                if (valueCallbacks != null) {
                    valueCallbacks!!.onReceiveValue(null)
                }
                valueCallbacks = filePathCallback
                val i = Intent(Intent.ACTION_GET_CONTENT)
                i.addCategory(Intent.CATEGORY_OPENABLE)
                if (fileChooserParams != null && fileChooserParams.acceptTypes != null
                        && fileChooserParams.acceptTypes.isNotEmpty()) {
                    i.type = fileChooserParams.acceptTypes[0]
                } else {
                    i.type = "*/*"
                }
                startActivityForResult(Intent.createChooser(i, "选择图片"), requestChooseFile)
                return true
            }
        }
    }

    private fun createPermissionTipDialog(): Dialog {
        return AlertDialog.Builder(this)
                .setTitle("警告").setMessage("请求权限申请异常。请前往应用设置页面允许必要的权限，否则将无法正常运行应用")
                .setNegativeButton("取消") { dialog, _ ->
                    dialog.dismiss()
                }.setPositiveButton("确认") { dialog, _ -> dialog.dismiss() }
                .setCancelable(false)
                .create()
    }

    private fun checkPermissions() {
        if (ContextCompat.checkSelfPermission(context(),
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
                PackageManager.PERMISSION_DENIED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                createPermissionTipDialog().show()
            } else {
                ActivityCompat.requestPermissions(this, arrayOf(""), 0x01)
            }
        } else {
            print(canGoBack)
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 0x01) {
            val temp = ArrayList<String>()

            for (i in grantResults.indices) {
                if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                    if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i])) {
                        createPermissionTipDialog().show()
                        return
                    } else {
                        temp.add(permissions[i])
                    }
                }
            }
            val tempArray = arrayOfNulls<String>(temp.size)
            if (tempArray.isNotEmpty()) {
                ActivityCompat.requestPermissions(this, temp.toArray(tempArray), 0x01)
                return
            }
            print(canGoBack)
        }
    }

    private fun print(canGoback: Boolean = false) {
//        //获取webview缩放率
//        val scale = webView.scale
//        //得到缩放后webview内容的高度
//        val webViewHeight = (webView.contentHeight*scale).toInt()
//        val bitmap = Bitmap.createBitmap(webView.width,webViewHeight, Bitmap.Config.ARGB_8888);
//        val canvas = Canvas(bitmap)
//        webView.draw(canvas)

        val width = webView.contentWidth
        val height = webView.contentHeight
        val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565)
        val canvas = Canvas(bitmap)
        webView.x5WebViewExtension.snapshotWholePage(canvas, false, false)
        bitmap.saveImage("天天趣玩", "${System.currentTimeMillis()}.jpg") {
            mHandler.post {
                scanPhoto(it)
                showToast("保存成功: $it")
                if (!canGoback) {
                    return@post
                }
                if (webView.canGoBack()) {
                    webView.goBack()
                } else {
                    finish()
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == requestChooseFile) {
            if (null == valueCallback && null == valueCallbacks) return

            val result = if (data == null || resultCode != RESULT_OK) null else data.data
            if (result == null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    valueCallbacks!!.onReceiveValue(null)
                    valueCallbacks = null
                } else {
                    valueCallback!!.onReceiveValue(null)
                    valueCallback = null
                }
                return
            }

            val path = FileUtils.getPath(this, result)
            if (TextUtils.isEmpty(path)) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    valueCallbacks!!.onReceiveValue(null)
                    valueCallbacks = null
                } else {
                    valueCallback!!.onReceiveValue(null)
                    valueCallback = null
                }
                return
            }

            val uri = Uri.fromFile(File(path))
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                valueCallbacks!!.onReceiveValue(arrayOf(uri))
                valueCallbacks = null
            } else {
                valueCallback!!.onReceiveValue(uri)
                valueCallback = null
            }
        }
    }

    override fun onResume() {
        super.onResume()
        // 所有的页面默认传入userId
        when {
            url!!.contains(API.LunTan) -> return
            url!!.endsWith(".html") -> {
                url += "?userId=${loginBean?.userId}"
            }
            !url!!.contains(API.LunTan) && !url!!.contains("&userId=") && !url!!.endsWith(".html") -> {
                url += "&userId=${loginBean?.userId}"
            }
            else -> {
            }
        }
        webView.loadUrl(url)
    }

    override fun onDestroy() {
        super.onDestroy()
        PayEventObserver.unregister(this)
        LoginObserver.unregister(this)
        webViewPresenter.detachView()
    }
}